//
//  UIDevice+Extension.swift
//  demo
//
//  Created by ZWJY on 2021/8/20.
//

import Foundation
import UIKit

// MARK: - 常见UI属性获取
public extension UIDevice {

    /// 当前屏幕与设计稿比例
    class var ratio: CGFloat { UIDevice.width/375.0 }

    /// 屏幕宽度
    class var width: CGFloat {
        min(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
    }

    /// 屏幕高度
    class var height: CGFloat {
        max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
    }
    
    /// 安全区域顶部间距
    class var safeTopH: CGFloat {
        let topH: CGFloat =  keyWindow?.safeAreaInsets.top ?? 0.0
        return topH > 0 ? topH : 10.0
    }
    
    /// 安全区域左边间距 - (应产品、UI邀请，不考虑安全区域，刘海，顾设置安全高度为0)
    ///      keyWindow?.safeAreaInsets.left ?? 0
    class var safeLeftH: CGFloat { 0.0 }

    /// 安全区域左边间距 - (应产品、UI邀请，不考虑安全区域，刘海，顾设置安全高度为0)
    ///      keyWindow?.safeAreaInsets.right ?? 0
    class var safeRightH: CGFloat { 0.0 }

    /// 安全区域左边间距
    class var safeBottomH: CGFloat {
        keyWindow?.safeAreaInsets.bottom ?? 0
    }

    /// 导航条高度
    class var navigtionHeight: CGFloat {
        statusHeight + navigtionBarHeight
    }

    ///tabBar高度
    class var tabBarHeight: CGFloat {
        safeBottomH + 49.0
    }

    ///导航栏高度
    class var navigtionBarHeight: CGFloat{
        if isiPad, let version = Double(UIDevice.current.systemVersion), version >= 12.0 {
            return 50
        }
        return 44
    }

    /// 获取状态栏高度
    class var statusHeight: CGFloat{
        guard isiPad else { return 20 }
        if #available(iOS 13.0, *) {
            let manager = UIApplication.shared.windows.last?.windowScene?.statusBarManager
            let hegith = manager?.statusBarFrame.height ?? 44
            return hegith
        }else{
            return UIApplication.shared.statusBarFrame.size.height
        }
    }

    /// 是否是iPad， ture是，false不是
    class var isiPad: Bool {
        UIDevice.current.userInterfaceIdiom == .pad
    }

    /// 主窗口
    class var keyWindow: UIWindow? {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.windows.last
        }
        return UIApplication.shared.keyWindow
    }

    /// 通过安全区域判断是否是刘海屏
    class var isNotchedScreen: Bool {

        if #available(iOS 11.0, *) {

            var window = self.keyWindow

            if window == nil {
                // keyWindow还没有创建时，通过创建临时window获取安全区域
                window = UIWindow(frame: UIScreen.main.bounds)
                if window!.safeAreaInsets.bottom <= 0 {
                    let viewController = UIViewController()
                    window?.rootViewController = viewController
                }
            }
            if window!.safeAreaInsets.bottom > 0 {
                return true
            }
        }else{
            return false
        }
        return false
    }
}


// MARK: - 软件信息
public extension UIDevice{
    
    /// 获取系统版本号
    class var currentSystemVersion: String { UIDevice.current.systemVersion }
    
    /// 获取系统名称
    class var currentSystemName: String { UIDevice.current.systemName }

    /// 当前设备名字
    class var currentDeviceName: String { UIDevice.current.name }

    /// 当前设备语言
    class var deviceLanguage: String { Bundle.main.preferredLocalizations[0] }

    /// 当前设备是不是模拟器
    class func isSimulator() -> Bool {
        var isSim = false
        #if arch(i386) || arch(x86_64)
        isSim = true
        #endif
        return isSim
    }

    /// UUID
    class var UUID: String? {
        return UIDevice.current.identifierForVendor?.uuidString
    }

    /// 当前设备是否越狱
    class var isJailbroken: Bool {
        if self.isSimulator() { return false }
        let paths = ["/Applications/Cydia.app", "/private/var/lib/apt/",
                     "/private/var/lib/cydia", "/private/var/stash"]
        for path in paths {
            if FileManager.default.fileExists(atPath: path) {
                return true
            }
        }
        let bash = fopen("/bin/bash", "r")
        if bash != nil {
            fclose(bash)
            return true
        }
        let path = String(format: "/private/%@", UUID ?? "")
        do {
            try "test".write(toFile: path, atomically: true, encoding: .utf8)
            try FileManager.default.removeItem(atPath: path)
            return true
        } catch {
            NSLog(error.localizedDescription)
        }
        return false
    }
}

// MARK: - 硬件信息
public extension UIDevice {
    /// 当前硬盘的空间
    class var diskSpace: Int64 {
        if let attrs = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) {
            if let space: NSNumber = attrs[FileAttributeKey.systemSize] as? NSNumber {
                if space.int64Value > 0 {
                    return space.int64Value
                }
            }
        }
        return -1
    }

    /// 当前硬盘可用空间
    class var diskSpaceFree: Int64 {
        if let attrs = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) {
            if let space: NSNumber = attrs[FileAttributeKey.systemFreeSize] as? NSNumber {
                if space.int64Value > 0 {
                    return space.int64Value
                }
            }
        }
        return -1
    }

    /// 当前硬盘已经使用的空间
    class var diskSpaceUsed: Int64 {
        let total = self.diskSpace
        let free = self.diskSpaceFree
        guard total > 0 && free > 0 else { return -1 }
        let used = total - free
        guard used > 0 else { return -1 }

        return used
    }

    /// 获取总内存大小
    class var memoryTotal: UInt64 {
        return ProcessInfo.processInfo.physicalMemory
    }

    /// 将大小转换成字符串用以显示
    class func fileSizeToString(fileSize:Int64) -> String {

        let fileSize1 = CGFloat(fileSize)

        let KB:CGFloat = 1024
        let MB:CGFloat = KB*KB
        let GB:CGFloat = MB*KB

        if fileSize < 10 {
            return "0 B"

        } else if fileSize1 < KB {
            return "< 1 KB"
        } else if fileSize1 < MB {
            return String(format: "%.1f KB", CGFloat(fileSize1)/KB)
        } else if fileSize1 < GB {
            return String(format: "%.1f MB", CGFloat(fileSize1)/MB)
        } else {
            return String(format: "%.1f GB", CGFloat(fileSize1)/GB)
        }
    }
}



